/**
 * header数据列表的分页组件
 */
let headerPageComponent;

/**
 * 用于存放message item列表的分页组件的map,
 * key 的格式为 messageId_{messageId}
 */
let pageComponentMap = {
};

/**
 * 为添加message的panel增加校验逻辑
 *
 * @param addLookPanel 添加message panel
 */
function addValidatorForEditLookPanel(addLookPanel) {
    addLookPanel.bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            code: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The code is required'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9\-\\.]+$/,
                        message: "Only characters, numbers, \"-\" or \".\" are allowed"
                    },
                    remote: {
                        type: 'GET',
                        headers: {
                            Authorization: JwtTokenUtils.getBearerHeader()
                        },
                        message: "No. already exists, please replace with a new one",
                        url: "/service/datacenter/message/checkMessageCodeExists",
                        delay: 1000
                    }
                }
            },
            name: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The name is required'
                    }
                }
            }
        }
    });
}

/**
 * 为添加message item的panel增加校验
 *
 * @param addMessageItemPanel 添加 message item的panel
 * @param messageId messageId
 */
function addValidatorForAddMessageItemPanel(addMessageItemPanel, messageId) {
    addMessageItemPanel.bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            code: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The code is required'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9\-\\.]+$/,
                        message: "Only characters, numbers, \"-\" or \".\" are allowed"
                    },
                    remote: {
                        type: 'GET',
                        headers: {
                            Authorization: JwtTokenUtils.getBearerHeader()
                        },
                        sync: false,
                        data: {
                            messageId: messageId
                        },
                        message: "No. already exists, please replace with a new one",
                        url: "/service/datacenter/message/checkMessageItemCodeExists",
                        delay: 1000
                    }
                }
            },
            name: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The name is required'
                    }
                }
            },
            value: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The value is required'
                    }
                }
            },
            order: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The order is required'
                    }
                }
            },
            lang: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The lang is required'
                    }
                }
            }
        }
    }).on('success.form.bv', function (e) {
        let messagePanel = $($(e.currentTarget).parents(".message-panel")[0]);
        addMessageItem(messagePanel);
    });
}

/**
 * 为修改message item的panel增加校验
 *
 * @param modifyItemDiv 修改 message item的panel
 */
function addValidatorForEditMessageItemPanel(modifyItemDiv) {
    modifyItemDiv.bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            name: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The name is required'
                    }
                }
            },
            value: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The value is required'
                    }
                }
            },
            order: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The order is required'
                    }
                }
            },
            lang: {
                group: '.input-div',
                validators: {
                    notEmpty: {
                        message: 'The lang is required'
                    }
                }
            }
        }
    });
}

/**
 * 添加Message
 * @param addLookPanel message添加面板
 */
function addMessage(addLookPanel) {
    let requestData = {};
    requestData.code = addLookPanel.find(".code-value").val();
    requestData.name = addLookPanel.find(".name-value").val();
    requestData.description = addLookPanel.find(".description-value").val();
    requestData.defaultContent = addLookPanel.find(".default-content-value").val();

    $.ajax({
        type: 'POST',
        url: "/service/datacenter/message/addMessage",
        contentType: "application/json;charset=UTF-8",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function () {
            addLookPanel.remove();
            $(".component .add-new-panel").removeClass("disable");
            $(".component .app-list").empty();
            headerPageComponent.query();
        }
    });
}

/**
 * 修改message
 *
 * @param updateMessagePanel message修改面板
 */
function updateMessage(updateMessagePanel) {
    let requestData = {};
    requestData.id = updateMessagePanel.attr("id");
    requestData.code = updateMessagePanel.find(".code-value").val();
    requestData.name = updateMessagePanel.find(".name-value").val();
    requestData.description = updateMessagePanel.find(".description-value").val();
    requestData.defaultContent = updateMessagePanel.find(".default-content-value").val();

    $.ajax({
        type: 'PUT',
        url: "/service/datacenter/message/updateMessage",
        contentType: "application/json;charset=UTF-8",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function () {
            headerPageComponent.refreshData();
        }
    });
}

/**
 * 查询message列表
 *
 * @param pageComponent 分页组件
 */
function queryMessages(pageComponent) {
    let requestData = {
        pageSize: pageComponent.size,
        pageNumber: pageComponent.number,
        query: pageComponent.queryParam
    };
    $.ajax({
        type: 'POST',
        url: "/service/datacenter/message/page/queryMessages",
        contentType: "application/json;charset=UTF-8",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function (data) {
            $(".component .data-list").empty();

            let pageParams = {};
            pageParams.totalPages = data.totalPages;
            pageParams.number = data.number;
            pageParams.size = data.size;

            pageComponent.rebuildHtmlDom(pageParams);

            let content = data.content;

            for (let i = 0; i < content.length; i++) {
                let message = content[i];
                let messagePanel = $(".component .templates .message-panel").clone();
                messagePanel.find(".panel-title").text(message.name);
                messagePanel.attr("id", message.id);
                messagePanel.css("display", "block");
                messagePanel.find(".id-value").text(message.id);
                messagePanel.find(".code-value").text(message.code);
                messagePanel.find(".name-value").text(message.name);
                messagePanel.find(".description-value").text(message.description);
                messagePanel.find(".default-content-value").text(message.defaultContent);

                messagePanel.find(".edit-button").click(function () {
                    let editMessagePanel = $(".component .templates .edit-data-panel").clone();
                    editMessagePanel.attr("id", message.id);
                    editMessagePanel.find(".panel-title").text("Modify Message");
                    editMessagePanel.find(".code-value").val(message.code);
                    editMessagePanel.find(".code-value").attr("disabled", "disabled");
                    editMessagePanel.find(".code-label").removeClass("required");
                    editMessagePanel.find(".name-value").val(message.name);
                    editMessagePanel.find(".description-value").text(message.description);

                    editMessagePanel.find(".save-button").click(function () {
                        editMessagePanel.bootstrapValidator('validate');
                        let invalidFields = editMessagePanel.data('bootstrapValidator').getInvalidFields();
                        if (invalidFields.length === 0) {
                            updateMessage(editMessagePanel);
                        }
                    });

                    editMessagePanel.find(".cancel-button").click(function () {
                        editMessagePanel.remove();
                        messagePanel.css("display", "block");
                    });

                    editMessagePanel.insertBefore($(this).parents(".data-panel"));

                    addValidatorForEditLookPanel(editMessagePanel);

                    messagePanel.css("display", "none");
                });

                messagePanel.find(".delete-button").click(function () {
                    PromptWindowUtils.showDeletePrompt("Are you sure to delete this message?", function () {
                        $.ajax({
                            type: 'DELETE',
                            url: "/service/datacenter/message/deleteMessage/" + message.id,
                            contentType: "application/json;charset=UTF-8",
                            headers: {
                                Authorization: JwtTokenUtils.getBearerHeader()
                            },
                            success: function () {
                                pageComponent.refreshData();
                                PromptWindowUtils.hideDeletePrompt();
                            }
                        });
                    });
                });

                messagePanel.find(".message-item-list-show-button").click(function () {
                    if ($(this).hasClass("open")) {
                        $(this).removeClass("open");
                        messagePanel.find(".item-table").removeClass("expansion");
                    } else if (messagePanel.find(".item-table").hasClass("queried")) {
                        $(this).addClass("open");
                        messagePanel.find(".item-table").addClass("expansion");
                    } else {
                        let messageId = messagePanel.attr("id");

                        let pageComponent = PageComponentUtils.createPageComponent({
                            size: 10,
                            number: 0,
                            container: messagePanel.find(".item-table"),
                            doQuery: (pageComponent) => {
                                queryMessageItems(pageComponent);
                            }
                        });

                        pageComponentMap["messageId" + messageId] = pageComponent;
                        pageComponent.query(messageId);
                    }
                });

                let addMessageItemPanel = messagePanel.find(".add-message-item-panel");
                addValidatorForAddMessageItemPanel(addMessageItemPanel, message.id);
                messagePanel.find(".add-message-item-button").click(function () {
                    addMessageItemPanel.addClass("show");
                });

                addMessageItemPanel.find(".show-other-attribute-button").click(function () {
                    let otherAttribute = addMessageItemPanel.find(".other-attribute");
                    if (otherAttribute.hasClass("show")) {
                        otherAttribute.removeClass("show");
                    }
                    else {
                        otherAttribute.addClass("show");
                    }
                });

                addMessageItemPanel.find(".close-button").click(function () {
                    addMessageItemPanel.removeClass("show");
                });

                addMessageItemPanel.find(".reset-button").click(function () {
                    addMessageItemPanel.find("input").val("");
                    addMessageItemPanel.find("textarea").val("");
                    addMessageItemPanel.data('bootstrapValidator').resetForm(false);
                });

                addMessageItemPanel.find(".ok-button").click(function () {
                    let bootstrapValidator = addMessageItemPanel.data('bootstrapValidator');
                    let invalidFields = bootstrapValidator.getInvalidFields();
                    if (invalidFields.length === 0) {
                        bootstrapValidator.resetForm(false);
                        bootstrapValidator.validate(); // 重新校验，再校验成功后由表单校验成功事件提交添加item的动作
                    }
                });

                $(".component .data-list").append(messagePanel);
            }
        }
    });
}

/**
 * 添加messageItem
 *
 * @param messagePanel messagePanel
 */
function addMessageItem(messagePanel) {
    let messageId = messagePanel.attr("id");
    let addMessageItemPanel = messagePanel.find(".add-message-item-panel");

    let requestData = {};
    requestData.lang = addMessageItemPanel.find(".lang-value").val();
    requestData.content = addMessageItemPanel.find(".content-value").val();
    requestData.messageId = messageId;

    $.ajax({
        type: 'POST',
        url: "/service/datacenter/message/addMessageItem",
        contentType: "application/json;charset=UTF-8",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function () {
            console.log("Add message item success ...");
            let pageComponent = pageComponentMap["messageId" + messageId];
            pageComponent.query();
        }
    });
}

/**
 * message item的修改按钮点击事件
 *
 * @param messageItemPanel message item panel
 * @param messageItem message item
 */
function handleModifyMessageItemButtonClick(messageItemPanel, messageItem) {
    if (messageItemPanel.children(".edit-item-panel").length !== 0) {
        return;
    }
    let modifyItemDiv = $(".component .templates .edit-item-panel").clone();
    modifyItemDiv.find(".lang-value").attr("disabled", "disabled");
    modifyItemDiv.find(".lang-value").val(messageItem.lang);
    modifyItemDiv.find(".content-value").val(messageItem.content);
    addValidatorForEditMessageItemPanel(modifyItemDiv);

    modifyItemDiv.find(".show-other-attribute-button").click(function () {
        let otherAttribute = modifyItemDiv.find(".other-attribute");
        if (otherAttribute.hasClass("show")) {
            otherAttribute.removeClass("show");
        }
        else {
            otherAttribute.addClass("show");
        }
    });

    modifyItemDiv.find(".cancel-button").click(function () {
        modifyItemDiv.remove();
    });
    modifyItemDiv.find(".save-button").click(function () {
        let invalidFields = modifyItemDiv.data('bootstrapValidator').getInvalidFields();
        if (invalidFields.length > 0) {
            return;
        }
        let requestData = {
            id: messageItem.id,
            content: modifyItemDiv.find(".content-value").val()
        };
        $.ajax({
            type: "PUT",
            contentType: "application/json;charset=utf-8",
            url: "/service/datacenter/message/updateMessageItem",
            dataType: "json",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: JSON.stringify(requestData),
            success: function () {
                let messagePanel = $(messageItemPanel.parents(".message-panel")[0]);
                let pageComponent = pageComponentMap["messageId" + messagePanel.attr("id")];
                pageComponent.refreshData();
            }
        });
    });
    modifyItemDiv.insertAfter(messageItemPanel.children(".self"));
}

/**
 * 查询message项
 *
 * @param pageComponent pageComponent
 */
function queryMessageItems(pageComponent) {
    let pageDiv = pageComponent.htmlDom;
    let dataPanel = $(pageDiv.parents(".data-panel")[0]);
    let requestData = {
        pageSize: pageComponent.size,
        pageNumber: pageComponent.number,
        query: pageComponent.queryParam
    };
    $.ajax({
        type: 'POST',
        contentType: "application/json;charset=UTF-8",
        url: "/service/datacenter/message/page/queryMessageItems",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: JSON.stringify(requestData),
        success: function (data) {
            let itemTable = dataPanel.find(".message-item-list-wrap .item-table");
            let itemList = itemTable.find(".item-list");
            itemList.empty();

            let pageParams = {};
            pageParams.totalPages = data.totalPages;
            pageParams.number = data.number;
            pageParams.size = data.size;

            pageComponent.rebuildHtmlDom(pageParams);

            let content = data.content;

            itemTable.addClass("expansion");
            if (!itemTable.hasClass("queried")) {
                itemTable.addClass("queried");
            }
            dataPanel.find(".item-list-show-button").addClass("open");
            for (let i = 0; i < content.length; i++) {
                let messageItem = content[i];
                let messageItemPanel = $(".component .templates .item-panel").clone();
                messageItemPanel.attr("id", messageItem.id);
                messageItemPanel.find(".id-div").text(messageItem.id);
                messageItemPanel.find(".lang-div").text(messageItem.lang);
                messageItemPanel.find(".content-div").text(messageItem.content);

                messageItemPanel.find(".modify-button").click(function () {
                    handleModifyMessageItemButtonClick(messageItemPanel, messageItem);
                });

                messageItemPanel.find(".delete-button").click(function () {
                    PromptWindowUtils.showDeletePrompt("Are you sure to delete this message item?", function () {
                        $.ajax({
                            type: 'DELETE',
                            url: "/service/datacenter/message/deleteMessageItem/" + messageItem.id,
                            contentType: "application/json;charset=UTF-8",
                            headers: {
                                Authorization: JwtTokenUtils.getBearerHeader()
                            },
                            success: function () {
                                pageComponent.refreshData();
                                PromptWindowUtils.hideDeletePrompt();
                            }
                        });
                    });
                });

                itemList.append(messageItemPanel);
            }
        }
    });
}

/**
 * 添加按钮点击事件处理
 * 添加新微服务div显示
 */
function addNewHandle() {
    if ($(".component .add-new-panel").hasClass("disable")) {
        return;
    }

    let addPanel = $(".component .templates .edit-data-panel").clone();
    addPanel.css("margin-bottom", "0");
    addPanel.find(".panel-title").text("Add Message");
    addPanel.find(".save-button").click(function () {
        addPanel.bootstrapValidator('validate');
        let invalidFields = addPanel.data('bootstrapValidator').getInvalidFields();
        if (invalidFields.length == 0) {
            addMessage(addPanel);
        }
    });

    addPanel.find(".cancel-button").click(function () {
        addPanel.remove();
        $(".component .add-new-panel").removeClass("disable");
    });

    addValidatorForEditLookPanel(addPanel);

    $(".component .add-div").append(addPanel);
    $(".component .add-new-panel").addClass("disable");
}

/**
 * 页面启动完成事件
 *
 */
$(document).ready(function () {
    headerPageComponent = PageComponentUtils.createPageComponent({
        size: 10,
        number: 0,
        container: $(".component .data-div"),
        queryParam: "",
        doQuery: (pg) => {
            queryMessages(pg);
        }
    });
    headerPageComponent.query();


    $(".component .query-div .operation-div .query-button").click(function () {
        let queryParam = $(".component .query-div .query-input").val();
        headerPageComponent.query(queryParam);
    });

    $(".component .query-div .query-form .query-input").keydown(function (e) {
        if (e.keyCode === 13) {
            let queryParam = $(".component .query-div .query-input").val();
            headerPageComponent.query(queryParam);
        }
    });
});
